// 封装通用的请求函数
function request(options) {
    return new Promise((resolve, reject) => {
        uni.request({
            url: options.url,
            data: options.data || {},
            method: options.method || "GET",
            success: (resp) => {
                console.log("请求成功，响应数据", resp);
                if (options.validateResponse &&!options.validateResponse(resp)) {
                    console.error("数据结构不符合预期", resp);
                    reject(new Error('数据结构不符合预期'));
                } else {
                    resolve(resp);
                }
            },
            fail: (err) => {
                console.error("请求失败", err);
                reject(err);
            }
        });
    });
}

// 使用封装后的 request 函数来获取位置信息
export function getLocation() {
    let key = "G2UBZ-RDHKB-JZBU2-NDLHV-YVZDZ-PEB42";
    return request({
        url: 'https://apis.map.qq.com/ws/location/v1/ip?key=' + key,
        method: "GET",
        validateResponse: (resp) => {
            return resp.data && resp.data.result && resp.data.result.location;
        }
    });
}

export function sesearchGas(latitude, longitude, keyWords, radius) {
    let key = "G2UBZ-RDHKB-JZBU2-NDLHV-YVZDZ-PEB42";
    let boundary = `nearby(${latitude},${longitude},${radius})`;

    let encodedKey = encodeURIComponent(key);
    let encodedKeyWords = encodeURIComponent(keyWords);
    let encodedBoundary = encodeURIComponent(boundary);
    let url = `https://apis.map.qq.com/ws/place/v1/search?key=${encodedKey}&keyword=${encodedKeyWords}&boundary=${encodedBoundary}`;

    return request({
        url: url,
        method: "GET",
        validateResponse: (resp) => {
            return resp.data && resp.data.status === 0;
        }
    });
}

export function getIP(address) {
    let key = "G2UBZ-RDHKB-JZBU2-NDLHV-YVZDZ-PEB42";
    return request({
        url: 'https://apis.map.qq.com/ws/geocoder/v1/?address='+address+"&key=" + key,
        method: "GET"
        
    });
}
